package com.itstudio.portal.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.itstudio.portal.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

@Component
public class JwtUtil {

    @Value("${spring.security.jwt.key}")
    private String key;

    @Value("${spring.security.jwt.expire}")
    private int expire;

    @Autowired
    StringRedisTemplate redisTemplate;

    //生成token
    public String createToken(UserInfo userInfo) {
        Algorithm algorithm =  Algorithm.HMAC256(key);

        Calendar calendar =  Calendar.getInstance();
        calendar.add(Calendar.HOUR, expire * 7);
        Date expireTime = calendar.getTime();

        return JWT.create()
                .withJWTId(userInfo.getUser().getId().toString())
                .withClaim("user", userInfo.getUsername())
                .withClaim("roles", userInfo.getPermissions())
                .withExpiresAt(expireTime)
                .withIssuedAt(new Date())
                .sign(algorithm);
    }

    //验证token
    public String  verifyToken(String token) {
        Algorithm algorithm =  Algorithm.HMAC256(key);
        try {
            DecodedJWT verify = JWT.require(algorithm).build().verify(token);
            if(verify.getExpiresAt().before(new Date())) return null;
            return verify.getId();
        } catch (JWTVerificationException e) {
            return null;
        }
    }

    public Date getExpireTime(String token) {
        Algorithm algorithm =  Algorithm.HMAC256(key);
        try {
            DecodedJWT verify = JWT.require(algorithm).build().verify(token);
            return verify.getExpiresAt();
        } catch (JWTVerificationException e) {
            return null;
        }
    }
}
